<?php

namespace common\models;

use Yii;
use common\components\Aliyunoss;
use common\components\Tools;
/**
 * This is the model class for table "net_config".
 *
 * @property int $id
 * @property int $cid
 * @property string $type
 * @property string $key
 * @property string $title
 * @property string $value
 * @property string $remark
 * @property int $sort
 * @property int $create_time
 * @property int $update_time
 */
class Config extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'net_config';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['cid', 'sort', 'create_time', 'update_time'], 'integer'],
            [['type', 'key'], 'required'],
            [['type', 'key'], 'string', 'max' => 32],
            [['title'], 'string', 'max' => 64],
            [['value'], 'string', 'max' => 255],
            [['remark'], 'string', 'max' => 128],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cid' => '类别',
            'type' => '类型',
            'key' => 'code',
            'title' => '标题',
            'value' => '内容',
            'remark' => '备注',
            'sort' => '排序',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
        ];
    }

    public function upload()
    {
        $Aliyunoss = new Aliyunoss('other3');
        if(!empty($this->value)){
            // 删除旧图片
            $resDelete = $Aliyunoss->deleteObject(Tools::removeEndPoint($this->value));
        }
        $key = '13network/config/'.date('Ymd').'/'.time().mt_rand(10000,99999).'.jpg';
        $file = $_FILES['file']['tmp_name'];
        $res = $Aliyunoss->uploadFile($key,$file);
       
        if(array_key_exists('info',$res) && $res['info']['http_code'] == 200){
            $photo_url = $res['info']['url'];
        }

        $this->value = $photo_url;
        $this->save();
    }

    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){
                $this->create_time = time();
                $this->update_time = time();
                if(empty($this->sort)){
                    $this->sort = 0;
                }
            }else{
                $this->update_time = time();
            }
            return true;
        }
        return false;
    }

    public function afterSave($insert, $changedAttributes)
    {
        Yii::$app->cache->flush();
    }

}
